package com.hhs.storage.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hhs.storage.bean.*;
import com.hhs.storage.dao.BaseLogsDao;
import com.hhs.storage.service.BaseLogsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhs.storage.service.BaseUserService;
import com.hhs.storage.util.SysUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hhs
 * @since 2022-12-16
 */
@Service
@Transactional
public class BaseLogsServiceImpl extends ServiceImpl<BaseLogsDao, BaseLogs> implements BaseLogsService {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private BaseUserService userService;
    @Resource
    private BaseUserService baseUserService;

    @Override
    public Map<String, Object> getAll(BaseLogs logs, InputParam inputParam) {
        QueryWrapper ew = new QueryWrapper<BaseLogs>();
        //模块名查询
        if (!StringUtils.isEmpty(logs.getModule())) {
            ew.like("module", logs.getModule());
        }
        //功能名查询
        if (!StringUtils.isEmpty(logs.getFunc())) {
            ew.like("func", logs.getFunc());
        }
        //操作人查询
        if (!StringUtils.isEmpty(logs.getUserId())) {
            ew.eq("user_id", logs.getUserId());
        }
        if (inputParam.getCreateTimeStartTime() != null) {//创建时间
            ew.ge("create_time", inputParam.getCreateTimeStartTime());
        }
        if (inputParam.getCreateTimeEndTime() != null) {//创建时间
            ew.le("create_time", inputParam.getCreateTimeEndTime());
        }
        ew.orderByDesc("create_time");
        Page<BaseLogs> result = this.page(new Page<BaseLogs>(
                inputParam.getPage(),
                inputParam.getSize()), ew);
        Map<String, Object> map = new HashMap<String, Object>();
        List<BaseLogs> list = result.getRecords();
        for (int i = 0; i < list.size(); i++) {
            BaseLogs logs1 = list.get(i);
            BaseUser user = userService.getById(logs1.getUserId());
            if (user != null) {
//                logs1.setUserName(user.getName());
            }
        }
        map.put("rows", list);
        map.put("total", result.getTotal());
        map.put("code", 1);
        return map;
    }

    @Override
    public Map<String, Object> getDayAll(String date) {
        LambdaQueryWrapper<BaseLogs> lqw = new LambdaQueryWrapper<>();
        lqw.eq(BaseLogs::getTableDate, date);
        lqw.orderByDesc(BaseLogs::getCreateTime);
        List<BaseLogs> list = this.list(lqw);

        Map<String, Map<String, List<BaseLogs>>> maps = new HashMap<>();

        list.forEach(item -> {
            JSONObject jsonObject = JSON.parseObject(item.getOldData());
            if (!jsonObject.get("workDate").equals(date)) {
                return;
            }
            BaseUser byId = baseUserService.getById(item.getUserId());
//            item.setUserName(byId.getName());

            String userId = (String) jsonObject.get("userId");

            Map<String, List<BaseLogs>> map = maps.get(userId);

            if (map == null) {
                Map<String, List<BaseLogs>> map1 = new HashMap<>();
                List<BaseLogs> list1 = new ArrayList<>();
                list1.add(item);
                map1.put(jsonObject.get("startTime") + "-" + jsonObject.get("endTime"), list1);
                maps.put(userId, map1);
                return;
            }

            List<BaseLogs> logs = map.get(jsonObject.get("startTime") + "-" + jsonObject.get("endTime"));
            if (logs == null) {
                List<BaseLogs> list1 = new ArrayList<>();
                list1.add(item);
                map.put(jsonObject.get("startTime") + "-" + jsonObject.get("endTime"), list1);
            } else {
                logs.add(item);
                map.put(jsonObject.get("startTime") + "-" + jsonObject.get("endTime"), logs);
            }
            maps.put(userId, map);
        });

        Map<String, Object> map = new HashMap<>();
        map.put("rows", maps);
        map.put("code", 1);
        return map;
    }

    @Override
    public Map<String, Object> getByIdAll(String userId, String module, LocalDate workDate, Boolean secondWeek) {
        //没有指定用户则查询当前用户
        if (StringUtils.isEmpty(userId)) {
            userId = SysUtil.getLoginUserId(request);
        }
        //没有指定日期则查询当前日期
        if (workDate == null) {
            workDate = LocalDate.now();
        }
        List<Map<String, Object>> data = new ArrayList<>();
        //获取当前周每日对象
        int index = workDate.getDayOfWeek().getValue();//当前周几
        for (int i = index - 1; i > 0; i--) {//前几天
            Map<String, Object> map = new HashMap<>();
            map.put("workDate", workDate.minusDays(i));
            data.add(map);
        }

        //当天
        Map<String, Object> temp = new HashMap<>();
        temp.put("workDate", workDate);
        data.add(temp);

        int day = 7;

        if (secondWeek && secondWeek != null) {
            day = 14;
        }

        //后几天
        for (int i = 1; i <= (day - index); i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("workDate", workDate.plusDays(i));
            data.add(map);
        }

        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        Map<String, Map<String, List<BaseLogs>>> maps = new HashMap<>();
        String finalUserId = userId;

        data.forEach(item -> {
            LocalDate workDates = (LocalDate) item.get("workDate");
            String workDate1 = workDates.format(fmt);
            LambdaQueryWrapper<BaseLogs> lqw = new LambdaQueryWrapper<>();
            lqw.eq(BaseLogs::getTableDate, workDate1);
            lqw.eq(BaseLogs::getSetUserId, finalUserId);
            lqw.orderByDesc(BaseLogs::getCreateTime);
            List<BaseLogs> list = this.list(lqw);
            list.forEach(items -> {
                BaseUser byId = baseUserService.getById(items.getUserId());
                items.setUserName(byId.getName());
                JSONObject jsonObject = JSON.parseObject(items.getOldData());
                Map<String, List<BaseLogs>> map = maps.get(workDate1);
                if (map == null) {
                    Map<String, List<BaseLogs>> map2 = new HashMap<>();
                    List<BaseLogs> list1 = new ArrayList<>();
                    list1.add(items);
                    map2.put(jsonObject.get("startTime") + "-" + jsonObject.get("endTime"), list1);
                    maps.put(workDate1, map2);
                    return;
                }
                List<BaseLogs> logs = map.get(jsonObject.get("startTime") + "-" + jsonObject.get("endTime"));
                if (logs == null) {
                    List<BaseLogs> list1 = new ArrayList<>();
                    list1.add(items);
                    map.put(jsonObject.get("startTime") + "-" + jsonObject.get("endTime"), list1);
                } else {
                    logs.add(items);
                    map.put(jsonObject.get("startTime") + "-" + jsonObject.get("endTime"), logs);
                }
                maps.put(workDate1, map);
            });
        });

        Map<String, Object> map = new HashMap<>();
        map.put("rows", maps);
        map.put("code", 1);
        return map;
    }

    @Override
    public Map<String, Object> getByIdList(String id) {
        QueryWrapper<BaseLogs> qw = new QueryWrapper<>();
        qw.eq("target_id", id);
        qw.orderByDesc("create_time");
        List<BaseLogs> list = this.list(qw);
        list.forEach(item -> {
            BaseUser byId = baseUserService.getById(item.getUserId());
            item.setUserName(byId.getName());
        });
        Map<String, Object> map = new HashMap<>();
        map.put("rows", list);
        map.put("code", 1);
        return map;
    }

    public void log(String module, String func, String paramStr) {
//        System.out.println(request);
        String user_id = SysUtil.getLoginUserId(request);
        log(user_id, module, func, paramStr);
    }

    @Override
    public void log(String userId, String module, String func, String paramStr) {
        BaseLogs logs = new BaseLogs();
        logs.setId(UUID.randomUUID().toString());
        logs.setUserId(userId);
        logs.setCreateTime(LocalDateTime.now());
        //手动设置参数
        logs.setModule(module);
        logs.setFunc(func);
        logs.setParamStr(paramStr);
//        this.baseMapper.insert(logs);
    }

    @Override
    public void log(String module, String func, String paramStr, Object oldData, String targetId, LocalDate tableDate, String setUserID) {
        String user_id = SysUtil.getLoginUserId(request);
        String oldDataStr = JSON.toJSONString(oldData);
        BaseLogs baseLogs = new BaseLogs();
        baseLogs.setUserId(user_id);
        baseLogs.setModule(module);
        baseLogs.setFunc(func);
        baseLogs.setParamStr(paramStr);
        baseLogs.setCreateTime(LocalDateTime.now());
        baseLogs.setOldData(oldDataStr);
        baseLogs.setTargetId(targetId);
        baseLogs.setTableDate(tableDate);
        baseLogs.setSetUserId(setUserID);
        this.save(baseLogs);
    }

    @Override
    public Map<String, Object> dele(String id) {
        this.baseMapper.deleteById(id);
        return ResponseInfo.success(null);
    }
}
